import os

import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.httpserver


# websocket 由 前后端, 双向通信, 共同编写逻辑!

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('client.html')

class EchoWebSocket(tornado.websocket.WebSocketHandler):
    def open(self):
        print("WebSocket opened")

    def on_message(self, message):
        print(f"Received message: {message}")
        self.write_message(f"You said: {message}")  # 发送给前端

    def on_close(self):
        print("WebSocket closed")

def make_app():
    return tornado.web.Application(
        [
            (r"/", MainHandler),
            (r"/websocket", EchoWebSocket),
        ],
        debug=True,
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
    )

if __name__ == "__main__":
    app = make_app()
    # server = tornado.httpserver.HTTPServer(app)
    # server.listen(8888)
    app.listen(8888)
    print("WebSocket server is running on ws://localhost:8888/websocket")
    tornado.ioloop.IOLoop.current().start()
